import { Injectable, NestMiddleware, Logger } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  private readonly logger = new Logger('HTTP');
  private readonly logEnabled: boolean;

  constructor(private readonly configService: ConfigService) {
    this.logEnabled = this.configService.get('LOG_ON', false);
  }

  use(req: Request, res: Response, next: NextFunction): void {
    if (!this.logEnabled) {
      return next();
    }

    const { method, originalUrl, ip, headers } = req;
    const userAgent = headers['user-agent'] || '';
    const startTime = Date.now();

    // 生成请求 ID
    const requestId = this.generateRequestId();
    req['requestId'] = requestId;

    // 记录请求开始
    this.logger.log(
      `[${requestId}] ${method} ${originalUrl} - ${ip} - ${userAgent}`
    );

    // 监听响应完成
    res.on('close', () => {
      const { statusCode } = res;
      const contentLength = res.get('content-length');
      const responseTime = Date.now() - startTime;

      this.logger.log(
        `[${requestId}] ${method} ${originalUrl} ${statusCode} ${contentLength || 0}b - ${responseTime}ms`
      );
    });

    next();
  }

  private generateRequestId(): string {
    return Math.random().toString(36).substring(2, 15) + 
           Math.random().toString(36).substring(2, 15);
  }
}
